package com.rzjm.exercise.module.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rzjm.exercise.common.base.controller.BaseController;
import com.rzjm.exercise.common.base.data.DataTableLayUI;
import com.rzjm.exercise.common.constant.Constant;
import com.rzjm.exercise.common.log.annotation.Log;
import com.rzjm.exercise.common.utils.*;
import com.rzjm.exercise.module.domain.*;
import com.rzjm.exercise.module.domain.excel.TerminalExcel;
import com.rzjm.exercise.module.domain.excel.TerminalFittingExcel;
import com.rzjm.exercise.module.service.TerminalFittingService;
import com.rzjm.exercise.module.service.CkTerminalService;
import com.rzjm.exercise.module.service.ShopService;
import com.rzjm.exercise.module.service.UserShopRelationService;
import com.rzjm.exercise.sys.core.dict.domain.DictDO;
import com.rzjm.exercise.sys.core.dict.service.DictService;
import com.rzjm.exercise.sys.system.user.domain.UserDO;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.zip.Zip64Mode;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.util.*;

/**
 * 设备
 *
 * @author mr.zhou
 * @email zhouwei_nice@163.com
 * @date 2020-12-15 22:36:23
 */

@Controller
@RequestMapping("/module/terminal")
public class TerminalController extends BaseController {
    @Resource
    private CkTerminalService ckTerminalService;
    @Resource
    private ShopService shopService;
    @Resource
    private DictService dictService;
    @Resource
    private UserShopRelationService userShopRelationService;
    @Resource
    private TerminalFittingService terminalFittingService;

    @Value("${projecturl.imgurl}")
    private String imgurl;
    @Value("${projecturl.uploadPath}")
    private String uploadPath;


    @Log("查询设备页面")
    @GetMapping("/{isClean}")
    @RequiresPermissions("module:terminal:terminal")
    String Terminal(Model model,@PathVariable("isClean") Integer isClean) {
        model.addAttribute("isClean",isClean);
        model.addAttribute("isBack",0);

        UserDO userDO = getUser();
        Map<String,Object> map = new HashMap<>();
        if(userDO.getUserType() == 2  || userDO.getUserType() == 13 || userDO.getUserType() == 14){//集团
            map.put("jituan_user_id",userDO.getGroupId());
        } else if(userDO.getUserType() == 3){//片区
            map.put("sys_user_id",userDO.getUserId());
        } else if(userDO.getUserType() == 4 || userDO.getUserType() == 5 || userDO.getUserType() == 6){//片区
            map.put("id",userDO.getShopId());
        }
        if (userDO.getGroupId() != null && userDO.getGroupId() > 0) {
            map.put("group_id", userDO.getGroupId());
        }
        List<Shop> list0 = shopService.getPageByUserId(map);
        model.addAttribute("shops", list0);
        return "module/terminal/terminal";
    }

    @Log("查询设备页面")
    @GetMapping("/shop/{shopId}")
    @RequiresPermissions("module:terminal:terminal")
    String ShopTerminal(Model model,@PathVariable("shopId") Integer shopId) {
        model.addAttribute("shopId",shopId);
        model.addAttribute("isBack",1);
        return "module/terminal/terminal";
    }

    @Log("查询设备")
    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("module:terminal:terminal")
    public DataTableLayUI<CkTerminal> list(DataTableLayUI<CkTerminal> condition) {
        UserDO userDO = getUser();
        Map<String,Object> map = condition.getSearchParams();
        String shopId = map.containsKey("search_eq_shopId") ? map.get("search_eq_shopId").toString(): null;
        String isClean = map.containsKey("search_eq_isClean") ? map.get("search_eq_isClean").toString(): null;
        String terminalNum = map.containsKey("search_like_terminalNum") ? map.get("search_like_terminalNum").toString():null;
        String checkTypeState = map.containsKey("checkTypeState") ? map.get("checkTypeState").toString(): null;
        String cleanTypeState = map.containsKey("cleanTypeState") ? map.get("cleanTypeState").toString(): null;

        Map<String,Object> map1 = new HashMap<>();
        map1.put("is_clean",0);
        if(userDO.getUserType() == 2){
            map1.put("group_id",userDO.getGroupId());
        } else if(userDO.getUserType() == 3){
            map1.put("pianqu_id",userDO.getPianquId());
        }else if(userDO.getUserType() == 4 || userDO.getUserType() == 5 || userDO.getUserType() == 6 || userDO.getUserType() == 10){
            map1.put("shop_id",userDO.getShopId());
        }
        if(StrUtil.isNotEmpty(shopId)){
            map1.put("shop_id",shopId);
        }
        DataTableLayUI<CkTerminal> dt = null;
        if(userDO.getUserType() >= 0){
            if(StrUtil.isNotEmpty(isClean)){
                map1.put("is_clean",Integer.parseInt(isClean));
            }
            if(StrUtil.isNotEmpty(checkTypeState)){
                map1.put("check0",Integer.parseInt(checkTypeState));
            }
            if(StrUtil.isNotEmpty(cleanTypeState)){
                map1.put("check1",Integer.parseInt(cleanTypeState));
            }
            if(StrUtil.isNotEmpty(terminalNum)){
                map1.put("terminal_num",terminalNum);
            }
        }
        map1.put("is_health",0);
        Page<CkTerminal> page = ckTerminalService.getPage(condition);
        List<CkTerminal> list = ckTerminalService.getPageByUserId(page,map1);
        list.forEach(terminal ->{
            Shop shop = shopService.findById(terminal.getShopId());
            if(shop != null){
                terminal.setShopName(shop.getShopName());
            }
            terminal.setQrcodeImg( imgurl + terminal.getQrcodeImg());
        });
        dt = ckTerminalService.pageSearchCustom(page,list,condition);
        return dt;
    }


    @Log("查询所有的待保养设备页面")
    @GetMapping("/health")
    @RequiresPermissions("module:terminal:fitting")
    String TerminalFittingNoHealth(Model model) {
        model.addAttribute("isBack",0);
        model.addAttribute("health",0);

        UserDO userDO = getUser();
        Map<String,Object> map = new HashMap<>();

        if(userDO.getUserType() == 2  || userDO.getUserType() == 13 || userDO.getUserType() == 14){//集团
            map.put("jituan_user_id",userDO.getGroupId());
        } else if(userDO.getUserType() == 3){//片区
            map.put("sys_user_id",userDO.getUserId());
        } else if(userDO.getUserType() == 4 || userDO.getUserType() == 5 || userDO.getUserType() == 6){//片区
            map.put("id",userDO.getShopId());
        }
        if (userDO.getGroupId() != null && userDO.getGroupId() > 0) {
            map.put("group_id", userDO.getGroupId());
        }
        List<Shop> list0 = shopService.getPageByUserId(map);
        model.addAttribute("shops", list0);

        return "module/terminal/health/health";
    }

    @Log("查询设备页面")
    @GetMapping("/fitting/{terminalId}")
    @RequiresPermissions("module:terminal:fitting")
    String TerminalFitting(Model model,@PathVariable("terminalId") Integer terminalId) {
        model.addAttribute("isBack",1);
        model.addAttribute("terminalId",terminalId);
        model.addAttribute("shopId",0);
        return "module/terminal/fitting/fitting";
    }

    @Log("查询设备")
    @ResponseBody
    @GetMapping("/fitting/list")
    @RequiresPermissions("module:terminal:fitting")
    public DataTableLayUI<TerminalFitting> fittinglist(DataTableLayUI<TerminalFitting> condition) {
        UserDO userDO = getUser();
        Map<String,Object> map = condition.getSearchParams();
        String shopId = map.containsKey("search_eq_shopId") ? map.get("search_eq_shopId").toString(): null;
        String terminalId = map.containsKey("search_eq_terminalId") ? map.get("search_eq_terminalId").toString(): null;
        String health = map.containsKey("health") ? map.get("health").toString(): null;
        String deviceFittingName = map.containsKey("search_like_deviceFittingName") ? map.get("search_like_deviceFittingName").toString(): null;

        Map<String,Object> map1 = new HashMap<>();
        map1.put("is_clean",2);

        if(userDO.getUserType() == 2){
            map1.put("group_id",userDO.getGroupId());
        } else if(userDO.getUserType() == 3){
            map1.put("pianqu_id",userDO.getPianquId());
        }else if(userDO.getUserType() == 4 || userDO.getUserType() == 5 || userDO.getUserType() == 6 || userDO.getUserType() == 10){
            map1.put("shop_id",userDO.getShopId());
        }
        if(StrUtil.isNotEmpty(shopId)){
            map1.put("shop_id",shopId);
        }

        map1.put("deviceFittingName",deviceFittingName);

        if(StrUtil.isNotEmpty(terminalId)){
            map1.put("terminalId",Integer.parseInt(terminalId));
        }
        if(StrUtil.isNotEmpty(health)){
            map1.put("health",Integer.parseInt(health));
        }
//        if (userDO.getGroupId() != null && userDO.getGroupId() > 0) {
//            map1.put("group_id", userDO.getGroupId());
//        }
        DataTableLayUI<TerminalFitting> dt = null;
        Page<TerminalFitting> page = terminalFittingService.getPage(condition);
        List<TerminalFitting> list = terminalFittingService.getPageByUserId(page,map1);
        list.forEach(fitting ->{
            CkTerminal terminal = ckTerminalService.findById(fitting.getTerminalId());
            if(terminal!=null){
                fitting.setTerminalNum(terminal.getTerminalNum());
                Shop shop = shopService.findById(terminal.getShopId());
                if(shop!=null){
                    fitting.setShopName(shop.getShopName());
                }
            }
        });
        dt = terminalFittingService.pageSearchCustom(page,list,condition);
        return dt;
    }


    @Log("待保养查询设备")
    @ResponseBody
    @GetMapping("/health/list")
    @RequiresPermissions("module:terminal:health")
    public DataTableLayUI<TerminalFitting> healthlist(DataTableLayUI<TerminalFitting> condition) {
        UserDO userDO = getUser();
        Map<String,Object> map = condition.getSearchParams();
        String shopId = map.containsKey("search_eq_shopId") ? map.get("search_eq_shopId").toString(): null;
        String health = map.containsKey("health") ? map.get("health").toString(): null;

        Map<String,Object> map1 = new HashMap<>();
        map1.put("is_clean",2);

        if(userDO.getUserType() == 2){
            map1.put("group_id",userDO.getGroupId());
        } else if(userDO.getUserType() == 3){
            map1.put("pianqu_id",userDO.getPianquId());
        }else if(userDO.getUserType() == 4 || userDO.getUserType() == 5 || userDO.getUserType() == 6 || userDO.getUserType() == 10){
            map1.put("shop_id",userDO.getShopId());
        }
        if(StrUtil.isNotEmpty(shopId)){
            map1.put("shop_id",shopId);
        }
        if(StrUtil.isNotEmpty(health)){
            map1.put("health",Integer.parseInt(health));
        }
        DataTableLayUI<TerminalFitting> dt = null;
        Page<TerminalFitting> page = terminalFittingService.getPage(condition);
        List<TerminalFitting> list = terminalFittingService.getPageByUserId(page,map1);
        list.forEach(fitting ->{
            CkTerminal terminal = ckTerminalService.findById(fitting.getTerminalId());
            if(terminal!=null){
                fitting.setTerminalNum(terminal.getTerminalNum());
                fitting.setTerminalName(terminal.getTerminalName());
                Shop shop = shopService.findById(terminal.getShopId());
                if(shop!=null){
                    fitting.setShopName(shop.getShopName());
                }
                fitting.setQrcodeImg( imgurl + terminal.getQrcodeImg());
            }
        });
        dt = terminalFittingService.pageSearchCustom(page,list,condition);
        return dt;
    }

    @Log("待保养查询设备")
    @ResponseBody
    @GetMapping("/health/list1")
    @RequiresPermissions("module:terminal:health")
    public DataTableLayUI<TerminalFitting> healthlist1(DataTableLayUI<TerminalFitting> condition) {
        UserDO userDO = getUser();
        Map<String,Object> map = condition.getSearchParams();
        String health = map.containsKey("health") ? map.get("health").toString(): null;

        Map<String,Object> map1 = new HashMap<>();
        map1.put("is_clean",2);

        if(userDO.getUserType() == 2){
            map1.put("group_id",userDO.getGroupId());
        } else if(userDO.getUserType() == 3){
            map1.put("pianqu_id",userDO.getPianquId());
        }else if(userDO.getUserType() == 4 || userDO.getUserType() == 5 || userDO.getUserType() == 6 || userDO.getUserType() == 10){
            map1.put("shop_id",userDO.getShopId());
        }
        if(StrUtil.isNotEmpty(health)){
            map1.put("health",Integer.parseInt(health));
        }
        DataTableLayUI<TerminalFitting> dt = null;
        Page<TerminalFitting> page = terminalFittingService.getPage(condition);
        List<TerminalFitting> list = terminalFittingService.getPageByUserId(page,map1);
        list.forEach(fitting ->{
            CkTerminal terminal = ckTerminalService.findById(fitting.getTerminalId());
            if(terminal!=null){
                fitting.setTerminalNum(terminal.getTerminalNum());
                Shop shop = shopService.findById(terminal.getShopId());
                if(shop!=null){
                    fitting.setShopName(shop.getShopName());
                }
            }
        });
        dt = terminalFittingService.pageSearchCustom(page,list,condition);
        return dt;
    }


    @Log("新增设备页面")
    @GetMapping("/add/{isclean}")
    @RequiresPermissions("module:terminal:add")
    String add(Model model,@PathVariable("isclean") Integer isclean) {
        CkTerminal terminal = new CkTerminal();
        terminal.setState(1);
        terminal.setIsClean(isclean);
        model.addAttribute("terminal", terminal);

        UserDO user = getUser();
        List<Shop> shops = new ArrayList<>();
        if(user.getUserType() == 0 || user.getUserType() == 1){//平台管理员可以查看所有的
            shops = shopService.selectAllList();
        } else if(user.getUserType() == 2){//集团管理员可以查看自己所管辖的
            Map<String,Object> map = new HashMap<>();
            map.put("jituan_user_id",user.getUserId());
            shops = shopService.getPageByUserId(map);
        } else if(user.getUserType() == 3){//片区管理员可以查看自己所管辖的
            Map<String,Object> map = new HashMap<>();
            map.put("sys_user_id",user.getUserId());
            shops = shopService.getPageByUserId(map);
        } else if(user.getUserType() == 4 || user.getUserType() == 5 || user.getUserType() == 6){//分厂和 巡检人员
            Map<String,Object> map = new HashMap<>();
            map.put("id",user.getShopId());
            shops = shopService.getPageByUserId(map);
        }
        model.addAttribute("shops", shops);
        return "module/terminal/detail";
    }

    @Log("编辑设备页面")
    @GetMapping("/edit/{id}")
    @RequiresPermissions("module:terminal:edit")
    String edit(@PathVariable("id") Integer id, Model model) {
        CkTerminal terminal = ckTerminalService.findById(id);
        if(terminal != null){
            Shop shop = shopService.findById(terminal.getShopId());
            if(shop!=null){
                terminal.setShopName(shop.getShopName());
            }
        }
        model.addAttribute("terminal", terminal);
        UserDO user = getUser();
        List<Shop> shops = new ArrayList<>();
        if(user.getUserType() == 0 || user.getUserType() == 1){//平台管理员可以查看所有的
            shops = shopService.selectAllList();
        } else if(user.getUserType() == 2 ){//集团管理员可以查看自己所管辖的
            Map<String,Object> map = new HashMap<>();
            map.put("jituan_user_id",user.getUserId());
            shops = shopService.getPageByUserId(map);
        }else if(user.getUserType() == 3){//片区管理员可以查看自己所管辖的
            Map<String,Object> map = new HashMap<>();
            map.put("sys_user_id",user.getUserId());
            shops = shopService.getPageByUserId(map);
        }  else if(user.getUserType() == 4 || user.getUserType() == 5 || user.getUserType() == 6){//分厂和片区
            Map<String,Object> map = new HashMap<>();
            map.put("id",user.getShopId());
            shops = shopService.getPageByUserId(map);
        }
        model.addAttribute("shops", shops);
        return "module/terminal/detail";
    }

    @Log("编辑设备页面")
    @GetMapping("/fitting/edit/{id}")
    @RequiresPermissions("module:terminal:edit")
    String editFitting(@PathVariable("id") Integer id, Model model) {
        TerminalFitting fitting = terminalFittingService.findById(id);
        model.addAttribute("fitting", fitting);
        return "module/terminal/fitting/detail";
    }

    /**
     * 保存
     */
    @Log("新增设备")
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("module:terminal:add")
    public R save(@Valid CkTerminal terminal) {
        QueryWrapper<CkTerminal> qw = new QueryWrapper<>();
        qw.eq("terminal_num",terminal.getTerminalNum());
        CkTerminal terminal1 = ckTerminalService.getOne(qw);
        if(terminal1!=null){
            return R.error("该设备编号已存在");
        }

        terminal.setCreateTime(new Date());
        try{
            String qrcode = "";
            String fileName = "terminal_qr_"+terminal.getShopId()+"_"+terminal.getTerminalNum()+".jpg";
            String content = "{\"qrtype\":\"terminal\",\"shop_id\":"+terminal.getShopId()+",\"num\":\""+terminal.getTerminalNum()+"\"}";
            Aes aes = new Aes();
            content = aes.encrypt(content);
            System.out.println("content:  "+ content);
            //上传头像到OSS
            String img_key = "";
            int upload_type = OssUtil.TYPE_TERMINAL_PHOTOS;
            img_key = OssUtil.getUploadPrefix(upload_type) + fileName;
            QRCodeUtilEx.createQrCodeImg(content, terminal.getTerminalName() +"   NO. "+ terminal.getTerminalNum(), null, uploadPath +"/"+ img_key, true);
            qrcode = img_key;
            terminal.setQrcodeImg(qrcode);
        }catch (Exception ex){
            ex.printStackTrace();
        }
        ckTerminalService.save(terminal);
        return R.ok();
    }


    /**
     * 下载二维码
     */
    @Log("下载二维码")
    @GetMapping("/download/{terminalNum}")
    public void download(@PathVariable("terminalNum") String terminalNum, HttpServletResponse response) {
        CkTerminal terminal = ckTerminalService.selectByUniqueColumn("terminal_num",terminalNum);
        if(terminal!=null){
            FileUtils.download(uploadPath + terminal.getQrcodeImg(),response);
        }
    }

    /**
     * 重置二维码
     */
    @Log("重置二维码")
    @PostMapping("/resetQrcode")
    @ResponseBody
    @RequiresPermissions("module:terminal:edit")
    public R resetQrcode( Integer id) {
        CkTerminal terminal = ckTerminalService.findById(id);
        if(terminal!=null){
            try{
                String qrcode = "";
                String fileName = "terminal_qr_"+terminal.getShopId()+"_"+terminal.getTerminalNum()+".jpg";
                String content = "{\"qrtype\":\"terminal\",\"shop_id\":"+terminal.getShopId()+",\"num\":\""+terminal.getTerminalNum()+"\"}";
                System.out.println("加密前的数据:  "+ content);
                Aes aes = new Aes();
                content = aes.encrypt(content);
                String img_key = "";
                int upload_type = OssUtil.TYPE_TERMINAL_PHOTOS;
                img_key = OssUtil.getUploadPrefix(upload_type) + fileName;
                System.out.println("加密后的数据:  "+ content);
                QRCodeUtilEx.createQrCodeImg(content, terminal.getTerminalName() +"   NO. "+ terminal.getTerminalNum(), null, uploadPath +"/"+ img_key, true);
                //上传头像到OSS
                qrcode = img_key;
                terminal.setQrcodeImg(qrcode);
            }catch (Exception ex){
                ex.printStackTrace();
            }
            if (ckTerminalService.updateById(terminal)) {
                return R.ok();
            }
        }
        return R.error();
    }


    @Log("批量新增设备页面")
    @GetMapping("/goBatchAdd")
    @RequiresPermissions("module:terminal:import")
    String goBatchAdd() {
        return "module/terminal/upload";
    }


    /**
     *  批量导入设备
     * @param file
     */
    @RequestMapping(value = "/readExcelBatchAdd", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("module:terminal:import")
    Object readExcel(@RequestParam(value="file", required = false) MultipartFile file){
        long t1 = System.currentTimeMillis();
        List<TerminalExcel> list = ExcelUtils.readExcel("", TerminalExcel.class, file);
        long t2 = System.currentTimeMillis();
        System.out.println(String.format("read over! cost:%sms", (t2 - t1)));
        UserDO user = getUser();
        list.forEach(b -> {
            boolean blIsHasQx = false;
            Shop shop = shopService.selectByUniqueColumn("shop_no",b.getShopNo().trim());
            if(shop != null) {
                if (user.getUserType() == 0 || user.getUserType() == 1) {
                    blIsHasQx = true;
                } else if (user.getUserType() == 2 ) {
                    QueryWrapper<UserShopRelation> qw = new QueryWrapper<>();
                    qw.eq("jituan_user_id", user.getUserId());
                    qw.eq("shop_id", shop.getId());
                    long relationCount = userShopRelationService.selectCountByQueryWrapper(qw);
                    if (relationCount > 0) {
                        blIsHasQx = true;
                    }
                } else if (user.getUserType() == 3) {
                    QueryWrapper<UserShopRelation> qw = new QueryWrapper<>();
                    qw.eq("sys_user_id", user.getUserId());
                    qw.eq("shop_id", shop.getId());
                    long relationCount = userShopRelationService.selectCountByQueryWrapper(qw);
                    if (relationCount > 0) {
                        blIsHasQx = true;
                    }
                } else if (user.getUserType() == 4 || user.getUserType() == 5 || user.getUserType() == 6) {
                    if (user.getShopId().intValue() == shop.getId().intValue()) {
                        blIsHasQx = true;
                    }
                }
                if (blIsHasQx) {
                    QueryWrapper<CkTerminal> qw = new QueryWrapper<>();
                    qw.eq("terminal_num", b.getTerminalNum());
                    qw.eq("shop_id", shop.getId());
                    boolean blExist = true;
                    CkTerminal terminal = ckTerminalService.getOne(qw);
                    if (terminal == null) {
                        terminal = new CkTerminal();
                        terminal.setState(1);
                        terminal.setIsClean(0);
                        terminal.setInTime(new Date());
                        terminal.setCreateTime(new Date());
                        terminal.setIsHealth(0);
                        blExist = false;
                    }
                    terminal.setTerminalNum(b.getTerminalNum());
                    terminal.setTerminalName(b.getTerminalName());
                    terminal.setSpecs("台");
                    if (shop != null) {
                        terminal.setShopId(shop.getId());
                    }
                    QueryWrapper<DictDO> qw0 = new QueryWrapper<>();
                    qw0.eq("type", "terminal-type");
                    qw0.eq("name", b.getTerminalType());
                    DictDO dict0 = dictService.getOne(qw0);
                    if (dict0 != null) {
                        terminal.setTerminalType(dict0.getValue());
                    }

                    Map<String,Object> mapCheck = getCycle(b.getCheckCycle());
                    if(mapCheck!=null && mapCheck.size() > 0){
                        terminal.setCheckCount((int)mapCheck.get("unit_count"));
                        terminal.setCheckCountUnit(mapCheck.get("unit").toString());
                    }

                    if (StrUtil.isNotEmpty(b.getCleanCycle())) {
                        Map<String,Object> mapClean = getCycle(b.getCleanCycle());
                        if(mapClean!=null && mapClean.size() > 0){
                            terminal.setCleanCount((int)mapClean.get("unit_count"));
                            terminal.setCleanCountUnit(mapClean.get("unit").toString());
                        }
                    }
                    if (!blExist || StrUtil.isNotEmpty(terminal.getQrcodeImg())) {
                        try {
                            String qrcode = "";
                            String fileName = "terminal_qr_" + shop.getId() + "_" + terminal.getTerminalNum() + ".jpg";
                            String content = "{\"qrtype\":\"terminal\",\"shop_id\":"+terminal.getShopId()+",\"num\":\"" + terminal.getTerminalNum() + "\"}";
                            Aes aes = new Aes();
                            content = aes.encrypt(content);
                            System.out.println("content:  " + content);

                            //上传头像到OSS
                            String img_key = "";
                            int upload_type = OssUtil.TYPE_TERMINAL_PHOTOS;
                            img_key = OssUtil.getUploadPrefix(upload_type) + fileName;
                            QRCodeUtilEx.createQrCodeImg(content, terminal.getTerminalName() + "  NO. " + terminal.getTerminalNum(), null, uploadPath + "/" + img_key, true);
                            qrcode = img_key;
                            terminal.setQrcodeImg(qrcode);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                    if (!blExist) {
                        ckTerminalService.save(terminal);
                    } else {
                        ckTerminalService.updateById(terminal);
                    }
                }
            }
        });
        return R.ok();
    }


    private Map<String,Object> getCycle(String cycleTxt){
        Map<String,Object> map = new HashMap<>();
        String checkCycle = cycleTxt.replaceAll("个","");
        String[] checkCycleArr = checkCycle.split("/");
        map.put("unit_count",Integer.parseInt(checkCycleArr[0]));
        QueryWrapper<DictDO> qw1 = new QueryWrapper<>();
        qw1.eq("type", "clean-cycle-type");
        String unit = checkCycleArr[1];
        //小时、季度、月、周
        //
        int unit_count = 0;
        String unitTxt = "";
        if(unit.contains("年") && !unit.contains("半")){
            unitTxt = "年";
            String ss = unit.replaceAll("年","");
            unit_count = !ss.equals("")? Integer.parseInt(ss):1;
        }else if(unit.contains("半年")){
            unitTxt = "半年";
            String ss = unit.replaceAll("半年","");
            unit_count = !ss.equals("")? Integer.parseInt(ss):1;
        }else if(unit.contains("季度")){
            unitTxt = "季度";
            String ss = unit.replaceAll("季度","");
            unit_count = !ss.equals("")? Integer.parseInt(ss):1;
        }else if(unit.contains("月")){
            unitTxt = "月";
            String ss = unit.replaceAll("月","");
            unit_count = !ss.equals("")? Integer.parseInt(ss):1;
        }else if(unit.contains("周")){
            unitTxt = "周";
            String ss = unit.replaceAll("周","");
            unit_count = !ss.equals("")? Integer.parseInt(ss):1;
        }else if(unit.contains("天")||unit.contains("班")){
            unitTxt = "天";
            String ss = unit.replaceAll("天","").replaceAll("班","");
            unit_count = !ss.equals("")? Integer.parseInt(ss):1;
        }else if(unit.contains("小时")){
            unitTxt = "小时";
            String ss = unit.replaceAll("小时","");
            unit_count = !ss.equals("")? Integer.parseInt(ss):1;
        }
        map.put("unit_count",unit_count);
        //半年、年 、天
        qw1.eq("name", unitTxt);
        DictDO dict1 = dictService.getOne(qw1);
        if (dict1 != null) {
            map.put("unit",dict1.getValue());
        }
        return map;
    }


    @Log("批量新增设备页面")
    @GetMapping("/goBatchAddFitting")
    @RequiresPermissions("module:terminal:import")
    String goBatchAddFitting() {
        return "module/terminal/uploadFitting";
    }

    /**
     *  批量导入设备保养点
     * @param file
     */
    @RequestMapping(value = "/excelBatchAddFitting", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("module:terminal:fitting:import")
    Object readExcelAddFitting(@RequestParam(value="file", required = false) MultipartFile file){
        long t1 = System.currentTimeMillis();
        List<TerminalFittingExcel> list = ExcelUtils.readExcel("", TerminalFittingExcel.class, file);
        long t2 = System.currentTimeMillis();
        System.out.println(String.format("read over! cost:%sms", (t2 - t1)));
        UserDO user = getUser();
        list.forEach(b -> {
            boolean blIsHasQx = false;
            Shop shop = shopService.selectByUniqueColumn("shop_no",b.getShopNum());
            if(shop != null){
                TerminalFitting fitting = new TerminalFitting();
                QueryWrapper<CkTerminal> qw = new QueryWrapper<>();
                qw.eq("terminal_num", b.getTerminalNum());
                qw.eq("shop_id", shop.getId());
                boolean blExist = true;
                CkTerminal terminal = ckTerminalService.getOne(qw);
                if (terminal == null) {
                    terminal = new CkTerminal();
                    terminal.setState(1);
                    terminal.setIsClean(0);
                    terminal.setCreateTime(new Date());
                    terminal.setInTime(new Date());
                    terminal.setIsHealth(1);
                    terminal.setSpecs("台");
                    blExist = false;
                    terminal.setTerminalNum(b.getTerminalNum());
                }
                terminal.setShopId(shop.getId());
                terminal.setTerminalName(b.getTerminalName());
                if (!blExist || StrUtil.isNotEmpty(terminal.getQrcodeImg())) {
                    try {
                        String qrcode = "";
                        String fileName = "terminal_qr_" + shop.getId() + "_" + terminal.getTerminalNum() + ".jpg";
                        String content = "{\"qrtype\":\"terminal\",\"shop_id\":"+terminal.getShopId()+",\"num\":\"" + terminal.getTerminalNum() + "\"}";
                        Aes aes = new Aes();
                        content = aes.encrypt(content);
                        System.out.println("content:  " + content);

                        //上传头像到OSS
                        String img_key = "";
                        int upload_type = OssUtil.TYPE_TERMINAL_PHOTOS;
                        img_key = OssUtil.getUploadPrefix(upload_type) + fileName;
                        QRCodeUtilEx.createQrCodeImg(content, terminal.getTerminalName() + "  NO. " + terminal.getTerminalNum(), null, uploadPath + "/" + img_key, true);
                        qrcode = img_key;
                        terminal.setQrcodeImg(qrcode);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
                int terminal_id = 0;
                if(!blExist){
                    ckTerminalService.save(terminal);
                }else{
                    ckTerminalService.updateById(terminal);
                }
                terminal_id = terminal.getId();
                if(terminal!=null){
                    fitting.setTerminalId(terminal_id);
                    if(shop != null) {
                        if (user.getUserType() == 0 || user.getUserType() == 1) {
                            blIsHasQx = true;
                        } else if (user.getUserType() == 2 ) {
                            QueryWrapper<UserShopRelation> qw1 = new QueryWrapper<>();
                            qw1.eq("jituan_user_id", user.getUserId());
                            qw1.eq("shop_id", shop.getId());
                            long relationCount = userShopRelationService.selectCountByQueryWrapper(qw1);
                            if (relationCount > 0) {
                                blIsHasQx = true;
                            }
                        } else if (user.getUserType() == 3) {
                            QueryWrapper<UserShopRelation> qw1 = new QueryWrapper<>();
                            qw1.eq("sys_user_id", user.getUserId());
                            qw1.eq("shop_id", shop.getId());
                            long relationCount = userShopRelationService.selectCountByQueryWrapper(qw1);
                            if (relationCount > 0) {
                                blIsHasQx = true;
                            }
                        } else if (user.getUserType() == 4 || user.getUserType() == 5 || user.getUserType() == 6) {
                            int shop_id = user.getShopId();
                            int shop_id1 = shop.getId();
                            if (shop_id == shop_id1) {
                                blIsHasQx = true;
                            }
                        }
                        if (blIsHasQx) {
                            fitting.setDeviceFittingName(b.getHealthInfo());
                            fitting.setHealthInfo(b.getHealthInfo());
                            fitting.setHealthRunhuaji(b.getHealthRunhuaji());
                            fitting.setRemark(b.getRemark());
                            if(StrUtil.isNotEmpty(b.getLastHealthTime())){
                                String s = b.getLastHealthTime().replaceAll("/","-");
                                fitting.setLastHealthTime(DateUtils.parseDate(s + " 00:00:00"));
                            }

                            if (StrUtil.isNotEmpty(b.getHealthCycle())) {
                                Map<String,Object> mapHealth = getCycle(b.getHealthCycle());
                                if(mapHealth!=null && mapHealth.size() > 0){
                                    fitting.setHealthCount((int)mapHealth.get("unit_count"));
                                    fitting.setHealthCountUnit(mapHealth.get("unit").toString());
                                }
                            }
                            terminalFittingService.save(fitting);
                        }
                    }
                }

            }
        });
        return R.ok();
    }


    /**
     * 通用下载请求
     * @param shopId 商户id
     * @param response
     * @param request
     */
    @GetMapping("/downloadQRcode")
    public void fileDownload(Integer shopId,HttpServletResponse response, HttpServletRequest request) {
        List<CkTerminal> terminals = ckTerminalService.selectListByColumn("shop_id",shopId);
        String outputFileName = System.currentTimeMillis() + "_共"+terminals.size()+".zip";
        try {
            // 设置response参数
            response.reset();
            response.setContentType("content-type:octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String((outputFileName).getBytes(), "iso-8859-1"));
            ServletOutputStream out = response.getOutputStream();
            ZipArchiveOutputStream zous = new ZipArchiveOutputStream(out);
            zous.setUseZip64(Zip64Mode.AsNeeded);
            List<File> fileList = new ArrayList<>();
            for (CkTerminal terminal : terminals) {
                fileList.add(new File(uploadPath + "/terminal/terminal_qr_"+shopId+"_"+ terminal.getTerminalNum() +".jpg"));
            }
            for (File file : fileList) {
                String file1 = file.getName();
//                String filen = file1.substring(0, file1.indexOf("_"));
//                filen += file1.substring(file1.indexOf("."));
                InputStream inputStream = new FileInputStream(file);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len;
                while ((len = inputStream.read(buffer)) != -1) {
                    baos.write(buffer, 0, len);
                }
                if (baos != null) {
                    baos.flush();
                }
                byte[] bytes = baos.toByteArray();
                //设置文件名
                ArchiveEntry entry = new ZipArchiveEntry(file1);
                zous.putArchiveEntry(entry);
                zous.write(bytes);
                zous.closeArchiveEntry();
                if (baos != null) {
                    baos.close();
                }
            }
            if (zous != null) {
                zous.close();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 修改
     */
    @Log("更新设备")
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("module:terminal:edit")
    public R update(@Valid CkTerminal terminal) {
        ckTerminalService.updateById(terminal);
        return R.ok();
    }


    /**
     * 修改
     */
    @Log("更新设备")
    @ResponseBody
    @RequestMapping("/fitting/update")
    @RequiresPermissions("module:terminal:fitting:edit")
    public R updateFitting(@Valid TerminalFitting fitting) {
        terminalFittingService.updateById(fitting);
        return R.ok();
    }


    /**
     * 删除
     */
    @Log("删除设备")
    @PostMapping( "/remove")
    @ResponseBody
    @RequiresPermissions("module:terminal:remove")
    public R remove( Integer id) {
        if (ckTerminalService.removeById(id)) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 删除
     */
    @Log("删除设备")
    @PostMapping("/fitting/remove")
    @ResponseBody
    @RequiresPermissions("module:terminal:fitting:remove")
    public R removefitting( Integer id) {
        if (terminalFittingService.removeById(id)) {
            return R.ok();
        }
        return R.error();
    }


    @RequiresPermissions("module:terminal:batchRemove")
    @Log("批量删除终端")
    @PostMapping("/batchRemove")
    @ResponseBody
    R batchRemove(@RequestParam("ids[]") Integer[] userIds) {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序");
        }
        if (ckTerminalService.removeByIds(Arrays.asList(userIds))) {
            return R.ok();
        }
        return R.error();
    }


    @RequiresPermissions("module:terminal:fitting:batchRemove")
    @Log("批量删除终端")
    @PostMapping("/fitting/batchRemove")
    @ResponseBody
    R batchRemoveFitting(@RequestParam("ids[]") Integer[] ids) {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序");
        }
        if (terminalFittingService.removeByIds(Arrays.asList(ids))) {
            return R.ok();
        }
        return R.error();
    }

    @RequiresPermissions("module:terminal:edit")
    @Log("批量生成二维码")
    @PostMapping("/batchQrcode")
    @ResponseBody
    R batchQrcode(@RequestParam("ids[]") Integer[] terminalIds) {
        int count = 0;
        for (Integer id : terminalIds){
            CkTerminal terminal = ckTerminalService.findById(id);
            if(terminal != null){
                try{
                    String qrcode = "";
                    String fileName = "terminal_qr_"+terminal.getShopId()+"_"+terminal.getTerminalNum()+".jpg";
                    String content = "{\"qrtype\":\"terminal\",\"shop_id\":"+terminal.getShopId()+",\"num\":\""+terminal.getTerminalNum()+"\"}";
                    System.out.println("加密前的数据:  "+ content);
                    Aes aes = new Aes();
                    content = aes.encrypt(content);
                    String img_key = "";
                    int upload_type = OssUtil.TYPE_TERMINAL_PHOTOS;
                    img_key = OssUtil.getUploadPrefix(upload_type) + fileName;
                    System.out.println("加密后的数据:  "+ content);
//                    QrCodeCreateUtil.createQRCode(900,900,content,uploadPath +"/"+ img_key);
                    QRCodeUtilEx.createQrCodeImg(content, terminal.getTerminalName() +"   NO. "+ terminal.getTerminalNum(), null, uploadPath +"/"+ img_key, true);

                    //上传头像到OSS
                    qrcode = img_key;
                    terminal.setQrcodeImg(qrcode);
                }catch (Exception ex){
                    ex.printStackTrace();
                }
                if (ckTerminalService.updateById(terminal)) {
                    count ++;
                }
            }
        }
        return R.ok("共成功"+count+"个");
    }
}
